
package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.sys.entity.DormAreaEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.form.PasswordForm;
import io.renren.modules.sys.service.DormAreaService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.http.protocol.HTTP;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private DormAreaService dormAreaService;


    /**
     * 所有用户列表
     */
    @GetMapping("/list")
//	@RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            params.put("createUserId", getUserId());
        }
        PageUtils page = sysUserService.queryPage(params);
        //获取真实宿舍号
        List<SysUserEntity> list = (List<SysUserEntity>) page.getList();
        List<Object> list1 = list.stream().map((entity) -> {
            if (entity.getDormId() != null) {
                DormAreaEntity byId = dormAreaService.getById(entity.getDormId());
                if (byId!=null && byId.getName()!=null && !byId.getName().equals("")){
                    entity.setDormId(Integer.parseInt(byId.getName()));
                }
            }
            return entity;
        }).collect(Collectors.toList());
        page.setList(list1);
        return R.ok().put("page", page);
    }

    /**
     * 所有用户列表
     */
    @GetMapping("/list01")
//	@RequiresPermissions("sys:user:list")
    public R list01(@RequestParam Map<String, Object> params) {

        PageUtils page = sysUserService.queryPage01(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        SysUserEntity entity = sysUserService.getById(getUserId());
        if (entity.getDormId() != null) {
            DormAreaEntity byId = dormAreaService.getById(entity.getDormId());
            if (byId!=null && byId.getName()!=null && !byId.getName().equals("")){
                entity.setDormId(Integer.parseInt(byId.getName()));
                //获取宿舍楼
                DormAreaEntity byId1 = dormAreaService.getById(byId.getParentId());
                entity.setSecondLevel(byId1.getName());
                //获取宿舍区
                DormAreaEntity byId2 = dormAreaService.getById(byId1.getParentId());
                entity.setFirstLevel(byId2.getName());
            }
        }
        return R.ok().put("data", entity);
    }

    /**
     * 修改登录用户密码
     */
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @PostMapping("/save")
//	@RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {

//		ValidatorUtils.validateEntity(user, AddGroup.class);
        user.setCreateUserId(getUserId());
        user.setCreateTime(new Date());
        user.setHeadImg("https://gulimall-lemonx.oss-cn-shenzhen.aliyuncs.com/2022-10-30/643e2096-4b72-474b-86ea-0bd443c101d7_%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20221030133858.jpg");
        List<Long> list = new ArrayList<>();
        list.add(user.getRoleId());
        user.setRoleIdList(list);
        sysUserService.saveUser(user);
        return R.ok();
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
//		ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return R.ok();
    }
}
